package com.example.orderfood2.RecyclerViewAdapter;

import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.orderfood2.R;

public class TeacherAdapter extends RecyclerView.Adapter<TeacherAdapter.ViewHolder>{
    private Cursor cursor;
    public TeacherAdapter(Cursor cursor){this.cursor=cursor;}
    private TeacherAdapter.OnItemClickListener listener; // 自定义接口，用于按钮点击回调
    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvId, tvUserName;
        Button btnEdit, btnDelete;

        public ViewHolder(View itemView) {
            super(itemView);
            // 初始化 TextView
            tvId = itemView.findViewById(R.id.tv_teacher_id);
            tvUserName = itemView.findViewById(R.id.tv_teacher_username);
            btnEdit=itemView.findViewById(R.id.btn_teacher_edit);
            btnDelete=itemView.findViewById(R.id.btn_teacher_delete);
        }
    }
    @NonNull
    @Override
    public TeacherAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_teacher, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull TeacherAdapter.ViewHolder holder, int position) {
        if (cursor.moveToPosition(position)) {
            int id = cursor.getInt(0);
            String username = cursor.getString(1);
            holder.tvId.setText(String.valueOf(id));
            holder.tvUserName.setText(username);
            holder.btnEdit.setOnClickListener(v->{
                if(listener!=null){
                    listener.onEditClick(position,id,username);
                }
            });
            // 删除按钮点击事件
            holder.btnDelete.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onDeleteClick(position, id);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return cursor.getCount();
    }
    // 定义点击事件接口
    public interface OnItemClickListener {
        void onEditClick(int position, int id, String username);
        void onDeleteClick(int position, int id);
    }
    // 设置监听器
    public void setOnItemClickListener(TeacherAdapter.OnItemClickListener listener) {this.listener =listener;}

    }
